import Events from '@/plugins/event';
import {
	SOCKET_HOST
} from '@/config';

class webScoket extends Events {
	options = {}
  
	constructor(uri) {
		super()
		this.isConnected = false //socket连接记录
		this.timer = null //心跳定时器
		this.uri = uri
		this.url = `${SOCKET_HOST}/websocket/${uri}`
		// this.url = `${SOCKET_HOST}`;
    
    my.connectSocket({
      url: this.url, // 开发者服务器接口地址，必须是 wss 协议，且域名必须是后台配置的合法域名
      header:{
        'content-type': 'application/json',
         'Authorization': ''
      },
      success: (res) => {
         console.log('WebSocket 连接成功',res);
      },
      fail: err => {
         console.log('WebSocket 连接失败2',err);
      }
    });
    my.onSocketOpen( ()=> {
      console.log(`WebSocket 已连接:${this.url}`)
      this.isConnected = true;
      clearInterval(this.timer);
      this.timer = setInterval(() => {
      	if (this.isConnected) {
      		const msg = JSON.stringify({
      			"code": 200,
      			"topic": 'heart',
      			'title': '保持连接'
      		})
      		this.send({
      			msg
      		})
      	}
      }, 40000)
      
    });
    my.onSocketMessage((res)=>{
      console.log('收到服务器内容：' + res.data);
      this.onPublish(this.uri, JSON.parse(res.data))
    });
    
	}
	close() {
		return new Promise((resolve, reject) => {
			if (this.isConnected) {
				clearInterval(this.timer);
        // 关闭 socket 连接
        my.closeSocket()
        my.offSocketOpen();
        my.offSocketMessage();
        my.onSocketClose((res)=> {
          this.isConnected = false;
          console.log('WebSocket 已关闭！')
        })
			}
			resolve()
		})
	}

	send(data) {
		console.log(data,'sendsendsendsendsend')
    my.sendSocketMessage({
      data:data.msg,
      fail: (res) => {
        // my.alert({ content: 'sendSocketMessage failed: ' + JSON.stringify(res) });
      }
    })
	}
}

export default webScoket
